<template>
  <div class="ele-body">
    <a-card :title="supplyMaterialModalApp.title" :bordered="false">
      <a-form ref="supplyMaterialForm"
              :model="supplyMaterialModalApp.supplyMaterial"
              :rules="supplyMaterialModalApp.rules"
              :label-col="{md: {span: 12}, sm: {span: 24}}"
              :wrapper-col="{md: {span: 12}, sm: {span: 24}}">
        <a-row :gutter="16">
          <a-col :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="供应材料名称:" name="name" >
              <a-input
                v-model:value="supplyMaterialModalApp.supplyMaterial.name"
                placeholder="请输入供应材料名称"
                class="ele-fluid"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="数量:" name="quantity" prop="quantity">
              <a-input-number
                ref="quantity"
                @blur="test"
                v-model:value="supplyMaterialModalApp.supplyMaterial.quantity"
                placeholder="请输入数量"
                @change="onQuantityChange"
                class="ele-fluid"
                :step="0.5"
                :min="0"
              ></a-input-number>
            </a-form-item>
          </a-col>

          <a-col :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="备注:" name="remark">
              <a-input
                v-model:value="supplyMaterialModalApp.supplyMaterial.remark"
                placeholder="选填"
                class="ele-fluid"
                :step="0.1"
                :min="0"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-row :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="supplyMaterialModalApp.display">
                <teleport to="#supplyMaterialOrderModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="supplyMaterialListApp.orderModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(supplyMaterialModalApp.supplyMaterial)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!supplyMaterialModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(supplyMaterialModalApp.supplyMaterial)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-row>
        </a-row>


      </a-form>
    </a-card>
  </div>
</template>

<script>
import {computed, defineComponent, inject, onMounted, reactive,ref} from "vue";
import regions from "ele-admin-pro/packages/regions";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import {SupplyMaterialService} from "@/views/restaurant/material/supplyMaterial/supplyMaterialService";
import {VXETable} from "vxe-table";
import {NumberMul} from "@/tool/number";


export default defineComponent({
  components: {},
  emits:['editClose'],
  setup(props, {emit}) {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    let routeId = route.params.id;
    let supplyMaterialListApp = inject('supplyMaterialListApp', reactive({}));
    let cartListGrid = inject('grid', reactive({}));
    const supplyMaterialForm = ref(null);
    const quantity = ref(null);
    console.log(cartListGrid)
    const reload = inject('reload',()=>{});
    const supplyMaterialModalApp = reactive({
      id: null,
      supplyMaterial: {},
      isEdit: false,
      display: false,
    });
    const cart = reactive(JSON.parse(localStorage.getItem('cart')) || []);
    // const goodsInfo = reactive({
    //   supplyMaterialId: null,
    //   quantity: null
    // })
    supplyMaterialModalApp.rules = {
      name: [
        {
          required: true,
          type: 'string',
          message: '请输入名称',
          trigger: 'blur'
        }
      ],
      quantity: [
        {
          required: true,
          type: 'number',
          message: '请输入数量',
          trigger: ['blur','change']
        }
      ],
      remark: [
        {
          required: false,
          type: 'string',
          message: '备注（选填）',
          trigger: 'blur'
        }
      ],

    }

    let itemTotalPrice = computed({
        get() {
          return NumberMul(supplyMaterialModalApp.supplyMaterial.price,supplyMaterialModalApp.supplyMaterial.quantity);
        }
        ,
        set(newVal) {
          supplyMaterialModalApp.title = `总价格 ${newVal}`
        }
      }
    )

    supplyMaterialModalApp.title = computed(()=>{
      return '总价格 '+(itemTotalPrice.value?itemTotalPrice.value:'0');
      }
    )
    // let cartTotalPrice = computed(() => {
    //   return NumberAdd(supplyMaterialModalApp.supplyMaterial.price,supplyMaterialModalApp.supplyMaterial.quantity);
    // })

    onMounted(() => {
      //清理数据
      supplyMaterialModalApp.supplyMaterial = reactive({});
      if (routeId) {//路由
        supplyMaterialModalApp.id = routeId;
        supplyMaterialModalApp.display = false;
        findSupplyMaterial(supplyMaterialModalApp.id);
      } else if (supplyMaterialListApp.orderModalForEdit) {//修改弹窗
        supplyMaterialModalApp.id = supplyMaterialListApp.currentId;
        if (supplyMaterialModalApp.id) findSupplyMaterial(supplyMaterialModalApp.id);
        console.log(supplyMaterialListApp.cart.supplierName)
        supplyMaterialModalApp.supplyMaterial.quantity = supplyMaterialListApp.cart.quantity;
        supplyMaterialModalApp.supplyMaterial.name = supplyMaterialListApp.cart.name;
        supplyMaterialModalApp.supplyMaterial.remark = supplyMaterialListApp.cart.remark;
        supplyMaterialModalApp.supplyMaterial.supplierName = supplyMaterialListApp.cart.supplierName;
        supplyMaterialModalApp.supplyMaterial.totalPrice = supplyMaterialListApp.cart.totalPrice;
        supplyMaterialModalApp.display = true;
      } else {
        supplyMaterialModalApp.id = supplyMaterialListApp.currentId;
        supplyMaterialModalApp.supplyMaterial.supplierName = supplyMaterialListApp.supplierName;
        if (supplyMaterialModalApp.id) findSupplyMaterial(supplyMaterialModalApp.id);
        supplyMaterialModalApp.display = true;
      }
      // supplyMaterialModalApp.supplyMaterial.quantity = 1;


    })
    const onQuantityChange = val => {
      // const {value} = e.target;
      supplyMaterialModalApp.supplyMaterial.quantity = val;
    }

    const findSupplyMaterial = (id) => {
      SupplyMaterialService.findSupplyMaterialForView(id).then((res) => {
        supplyMaterialModalApp.supplyMaterial = res.data;
        //TODO:为编辑准备.
        if(supplyMaterialListApp.orderModalForEdit){
          supplyMaterialModalApp.supplyMaterial.quantity = supplyMaterialListApp.cart.quantity;
          supplyMaterialModalApp.supplyMaterial.remark = supplyMaterialListApp.cart.remark;
        }
        supplyMaterialModalApp.title = "总金额 " + (itemTotalPrice.value ? itemTotalPrice.value : '0');
      }).catch(error => {
        VXETable.modal.message({content: `查找出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:材料加入到采购单 新增&编辑*/
    const onSubmit = (goodsInfo) => {
      // debugger;
      console.log(goodsInfo)
      supplyMaterialForm.value.validate().then(()=>{
        //修改
        if(supplyMaterialListApp.orderModalForEdit){
          let index = cart.findIndex(item => {
            // console.log(item.eid)
            return item.eid == goodsInfo.eid
          });
          cart[index].quantity = goodsInfo.quantity;
          cart[index].totalPrice = itemTotalPrice.value;
          if (goodsInfo.remark){
            cart[index].remark = goodsInfo.remark;
          }
          console.log(cartListGrid)
          // cartListGrid.loadData(cart);
        }
        else{
          //新增
          console.log(goodsInfo.eid)
          let index = cart.findIndex(item => {
            // console.log(item.eid)
            return item.eid == goodsInfo.eid
          });
          console.log(index)
          if (index == -1) {
            goodsInfo.totalPrice = itemTotalPrice.value;
            cart.push(goodsInfo);
          } else {
            console.log(cart[index])
            console.log(goodsInfo)
            cart[index].quantity += goodsInfo.quantity;
            cart[index].supplierName = goodsInfo.supplierName;
            cart[index].remark = goodsInfo.remark;
            cart[index].totalPrice += itemTotalPrice.value;
          }
        }
        localStorage.setItem('cart', JSON.stringify(cart));
        VXETable.modal.message({content: '加入采购单成功', status: 'success'});
        console.log(cart)
        supplyMaterialListApp.orderModalShowing = false;
        emit('editClose',true)
      })
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      router.push(`/restaurant/material/supplyMaterial`);
      store.dispatch('user/tabRemove', route.fullPath);

    }
    const test = () =>{

      console.log(quantity.value)
    }
    return {
      cityData,
      routeId,
      supplyMaterialListApp,
      supplyMaterialModalApp,
      cartListGrid,
      supplyMaterialForm,
      quantity,
      onSubmit,
      reload,
      continueSubmit,
      onBack,
      onQuantityChange,
      test
    }

  },
})
</script>

<style scoped>

</style>
